package com.itboye.mengwu.app.ui.mymeng;

import java.util.ArrayList;
import java.util.Observable;
import java.util.Observer;

import android.content.Context;
import android.content.Intent;
import android.graphics.Paint;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.itboye.config.GlobalConfig;
import com.itboye.core.alert.ByAlert;
import com.itboye.core.object.BaseFragment;
import com.itboye.core.object.ResultEntity;
import com.itboye.core.object.SpPublicParams;
import com.itboye.core.utils.SPUtils;
import com.itboye.core.utils.XImageLoader;
import com.itboye.mengwu.R;
import com.itboye.mengwu.app.ui.main.PingLunBaoBeiActivity;
import com.itboye.mengwu.app.ui.main.TuiKuanXiangQingActivity;
import com.itboye.mengwu.app.ui.web.WebActivity;
import com.itboye.mengwu.buy.ui.DaiFuKuanDetail;
import com.itboye.mengwu.data.model.OrderBean;
import com.itboye.mengwu.data.model.OrderQueryModel;
import com.itboye.mengwu.data.presenter.OrderPresenter;
import com.itboye.mengwu.widget.XListView;
import com.itboye.mengwu.widget.XListView.IXListViewListener;

public class FragmentDaiPingJia extends BaseFragment implements Observer,
		IXListViewListener {

	RelativeLayout re_nodata;
	XListView listView;
	OrderPresenter orderPresenter;
	private ArrayList<OrderQueryModel.OrderList> model = new ArrayList<OrderQueryModel.OrderList>();
	private MyAdapter adapter;
	public String type;
	protected String uid;
	int pageNo = 1;
	String shuaxinType = "";
	OrderQueryModel orderQueryModel;
	OrderBean orderBean = new OrderBean();
	TextView dengdaipingjia;// 买家付款状态

	public FragmentDaiPingJia(String type) {
		this.type = type;
	}

	@Override
	public int initView() {
		// TODO Auto-generated method stub
		return R.layout.fragment_myorder;
	}

	@Override
	public void onMyActivityCreated() {
		listView.setXListViewListener(this);
		listView.setPullLoadEnable(true);
		listView.setPullRefreshEnable(true);
		uid = SPUtils.get(getActivity(), null, SpPublicParams.UID, "") + "";
		// showProgressDialog("数据加载中,请稍后", true);
		adapter = new MyAdapter(getActivity(), R.layout.item_wait_pay, model);
		listView.setAdapter(adapter);

		orderPresenter = new OrderPresenter(this);
		orderBean.setUid(SPUtils.get(getActivity(), null, SpPublicParams.UID,
				"") + "");
		orderBean.setPageNo(pageNo + "");
		orderBean.setStatus(type);
		orderPresenter.getInfo(orderBean);
		listView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				// TODO Auto-generated method stub
				if (type.equals("5")) {
					Log.e("hu", model.get(position - 1).getId());
					Log.e("hu", type);

					Intent intent = new Intent(getActivity(),
							TuiKuanXiangQingActivity.class);
					intent.putExtra("orderId", model.get(position - 1).getId());
					intent.putExtra("type", type);
					startActivity(intent);
				} else {
					Intent intent = new Intent(getActivity(),
							DaiFuKuanDetail.class);
					intent.putExtra("model", model.get(position - 1));
					intent.putExtra("id", model.get(position - 1).getId());
					intent.putExtra("type", type);
					startActivity(intent);
				}
			}
		});
	}

	public class MyAdapter extends BaseAdapter {
		Context context;
		int resID;
		ArrayList<OrderQueryModel.OrderList> model;

		public MyAdapter(Context context, int resID,
				ArrayList<OrderQueryModel.OrderList> model) {
			this.context = context;
			this.resID = resID;
			this.model = model;
		}

		@Override
		public int getCount() {
			return model == null ? 0 : model.size();
		}

		@Override
		public Object getItem(int position) {
			return model.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(final int position, View convertView,
				ViewGroup parent) {
			int count = 0;
			Holder viewHolder = null;
			if (viewHolder == null) {
				viewHolder = new Holder();
				convertView = LayoutInflater.from(context).inflate(
						R.layout.item_wait_get_goods, null);
				viewHolder.querenshouhuo = (Button) convertView
						.findViewById(R.id.querenshouhuo);
				viewHolder.tuikuan = (Button) convertView
						.findViewById(R.id.tuikuan);
				viewHolder.wuliu = (Button) convertView
						.findViewById(R.id.btn_1);
				viewHolder.yunfei = (TextView) convertView
						.findViewById(R.id.yunfei);
				viewHolder.total_num_tv = (TextView) convertView
						.findViewById(R.id.total_num_tv);
				viewHolder.goodsgroup = (LinearLayout) convertView
						.findViewById(R.id.goodsgroup);
				viewHolder.total_price = (TextView) convertView
						.findViewById(R.id.total_price);
				viewHolder.wait_pay_tv = (TextView) convertView
						.findViewById(R.id.wait_pay_tv);
				viewHolder.li_wodeshouhou = (RelativeLayout) convertView
						.findViewById(R.id.li_wodeshouhou);
				viewHolder.total_price_tv = (TextView) convertView
						.findViewById(R.id.total_price_tv);
				viewHolder.jiaoyijine = (TextView) convertView
						.findViewById(R.id.jiaoyijine);
				viewHolder.tuikuanjine = (TextView) convertView
						.findViewById(R.id.tuikuanjine);
				convertView.setTag(viewHolder);
			} else {
				viewHolder = (Holder) convertView.getTag();
			}
			viewHolder.goodsgroup.removeAllViews();
			for (int i = 0; i < model.get(position).getItems().size(); i++) {
				View childView = LayoutInflater.from(getActivity()).inflate(
						R.layout.goods_item, null);
				((TextView) childView.findViewById(R.id.dangge_shuliang))
						.setText("x"
								+ model.get(position).getItems().get(i)
										.getCount());
				((TextView) childView.findViewById(R.id.goods_old_price))
						.setText("￥"
								+ model.get(position).getItems().get(i)
										.getOriPrice());
				((TextView) childView.findViewById(R.id.goods_old_price))
						.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG); // 中划线
				XImageLoader.load(GlobalConfig.API_URL + "/picture/index?id="
						+ model.get(position).getItems().get(i).getImgUrl(),
						((ImageView) childView.findViewById(R.id.wait_pay_iv)));
				((TextView) childView.findViewById(R.id.goods_price))
						.setText("￥"
								+ model.get(position).getItems().get(i)
										.getPrice());
				((TextView) childView.findViewById(R.id.goodsname_tv))
						.setText(model.get(position).getItems().get(i)
								.getName());
				((TextView) childView.findViewById(R.id.buy_num)).setText(model
						.get(position).getItems().get(i).getSkuDesc());
				count += Integer.parseInt(model.get(position).getItems().get(i)
						.getCount());
				viewHolder.goodsgroup.addView(childView);
			}
			viewHolder.total_num_tv.setText("共" + count + "件商品");
			viewHolder.tuikuan.setVisibility(View.GONE);
			if (type.equals("1")) {
				viewHolder.wait_pay_tv.setText("代付款");
			}
			if (type.equals("3")) {
				// if(model.get(position).getPayStatus().equals("0")){//待支付
				//
				// }else
				// if(model.get(position).getPayStatus().equals("1")){//已支付（等待发货，等待收货）
				//
				// }if(model.get(position).getPayStatus().equals("0")){//待支付
				//
				// }if(model.get(position).getPayStatus().equals("0")){//待支付
				//
				// }
				viewHolder.wuliu.setText("查看物流");
				viewHolder.tuikuan.setText("退款");
				viewHolder.querenshouhuo.setText("确认收货");
				viewHolder.tuikuan.setVisibility(View.VISIBLE);
				viewHolder.wuliu.setVisibility(View.VISIBLE);
				viewHolder.wait_pay_tv.setText("待收货");
				viewHolder.querenshouhuo.setVisibility(View.VISIBLE);
			}
			if (type.equals("6")) {// 待评价区域
				viewHolder.wait_pay_tv.setText("已处理");
				if (model.get(position).getCsStatus().equals("2")) {
					viewHolder.wait_pay_tv.setText("待处理");
				} else if (model.get(position).getCsStatus().equals("3")) {
					viewHolder.wait_pay_tv.setText("已处理");
				}
				// if(model.get(position).getOrderStatus().equals("5")){
				// viewHolder.wait_pay_tv.setText("带评价");
				// }
				viewHolder.wuliu.setText("查看物流");
				viewHolder.tuikuan.setVisibility(View.GONE);
				viewHolder.querenshouhuo.setText("去评价");
				viewHolder.wuliu.setVisibility(View.VISIBLE);
				viewHolder.querenshouhuo.setVisibility(View.VISIBLE);
			}
			if (type.equals("5")) {// 售后区域
				viewHolder.li_wodeshouhou.setVisibility(View.VISIBLE);
				viewHolder.wuliu.setVisibility(View.GONE);
				viewHolder.tuikuan.setVisibility(View.GONE);
				viewHolder.total_price_tv.setVisibility(View.GONE);
				viewHolder.total_price.setVisibility(View.GONE);
				viewHolder.yunfei.setVisibility(View.GONE);
				viewHolder.querenshouhuo.setText("查看详情");
				if (model.get(position).getCsStatus().equals("2")) {

					viewHolder.wait_pay_tv.setText("待处理");
					// viewHolder.li_wodeshouhou.setVisibility(View.GONE);
				} else if (model.get(position).getCsStatus().equals("3")) {
					viewHolder.wait_pay_tv.setText("退款完成");
					// viewHolder.li_wodeshouhou.setVisibility(View.VISIBLE);
				}
				viewHolder.jiaoyijine.setText(model.get(position).getPrice());
				// viewHolder.tuikuanjine.setText(model.get(position).getPostPrice());
				viewHolder.querenshouhuo.setVisibility(View.VISIBLE);
			}
			viewHolder.tuikuan.setOnClickListener(new OnClickListener() {// Button
																			// two

						@Override
						public void onClick(View v) {
							// TODO Auto-generated method stub
							if (type.equals("3")) {
								//ByAlert.alert("待收货---->退款");
							}
							if (type.equals("6")) {
								ByAlert.alert("2");
							}
							if (type.equals("5")) {
								ByAlert.alert("3");
							}
							//
							// Intent intent = new Intent(getActivity(),
							// WebActivity.class);
							// intent.putExtra("title", "物流查询");
							// intent.putExtra("url",
							// SpPublicParams.Logistics_URL
							// + model.get(position).getOrderCode());
							// startActivity(intent);
						}
					});
			viewHolder.querenshouhuo.setTag(position);
			viewHolder.querenshouhuo.setOnClickListener(new OnClickListener() {// Button
																				// three

						@Override
						public void onClick(View v) {
							// TODO Auto-generated method stub
							if (type.equals("3")) {

								//ByAlert.alert("待收货---->确认收货");
								orderPresenter.makesureOrder(uid,
										model.get(position).getOrderCode());
							}
							if (type.equals("6")) {
								//ByAlert.alert("5");
								Intent intent = new Intent(getActivity(),
										PingLunBaoBeiActivity.class);
								intent.putExtra("model", model.get(position));
								startActivity(intent);
							}
							if (type.equals("5")) {
								Intent intent = new Intent(getActivity(),
										TuiKuanXiangQingActivity.class);
								intent.putExtra("orderId",
										model.get((int) v.getTag()).getId());
								startActivity(intent);
							}

						}
					});
			viewHolder.wuliu.setOnClickListener(new OnClickListener() {// Button
						// one

						@Override
						public void onClick(View v) {
							// TODO Auto-generated method stub
							if (type.equals("3") || type.equals("6")) {
								ByAlert.alert("7");
								Intent intent = new Intent(getActivity(),
										WebActivity.class);
								intent.putExtra("title", "物流查询");
								intent.putExtra(
										"url",
										SpPublicParams.Logistics_URL
												+ model.get(position)
														.getOrderCode()
												+ "&uid="
												+ uid
												+ "&psw="
												+ SPUtils
														.get(getActivity(),
																null,
																SpPublicParams.PASSWORD,
																""));
								startActivity(intent);
							}
							if (type.equals("5")) {
								ByAlert.alert("8");
							}

						}
					});

			viewHolder.jiaoyijine
					.setText("￥"
							+ (Double.parseDouble(model.get(position)
									.getPrice())
									- Double.parseDouble(model.get(position)
											.getDiscountMoney()) + Double
										.parseDouble(model.get(position)
												.getPostPrice())) + "");
			// viewHolder.tuikuanjine.setText(model.get(position).getr);
			// viewHolder.yunfei.setText("(含运费￥"
			// + model.get(position).getPostPrice() + ")");
			return convertView;
		}

		class Holder {
			private Button wuliu, tuikuan, querenshouhuo;
			TextView total_num_tv, goodsname_tv, buy_num, goods_price,
					total_price_tv, jiaoyijine, tuikuanjine, total_price,
					yunfei, wait_pay_tv;
			LinearLayout goodsgroup;
			RelativeLayout li_wodeshouhou;
			ImageView wait_pay_iv;
		}

	}

	@Override
	public void update(Observable observable, Object data) {
		// TODO Auto-generated method stub
		ResultEntity entity = handlerError(data);
		if (entity != null) {
			if (entity.getEventType() == OrderPresenter.OrderQuerySuccess) {
				orderQueryModel = (OrderQueryModel) entity.getData();
				if (shuaxinType.equals("refresh"))
					model.clear();
				model.addAll(orderQueryModel.getList());
				adapter.notifyDataSetChanged();
				if (model.size() > 0) {
					re_nodata.setVisibility(View.GONE);
					listView.setVisibility(View.VISIBLE);
				} else {
					re_nodata.setVisibility(View.VISIBLE);
					listView.setVisibility(View.GONE);
				}
			} else if (entity.getEventType() == OrderPresenter.OrderQueryFail) {

			} else if (entity.getEventType() == OrderPresenter.OrderSureSuccess) {
				ByAlert.alert(entity.getData() + "");
				orderPresenter.getInfo(orderBean);
			} else if (entity.getEventType() == OrderPresenter.OrderSureFail) {
				ByAlert.alert(entity.getData() + "");
			}
		}
		try {
			closeProgressDialog();
		} catch (Exception e) {
			// TODO: handle exception
		}
		try {
			stopLoad();
		} catch (Exception e) {
			// TODO: handle exception
		}
	}

	@Override
	public void onRefresh() {
		shuaxinType = "refresh";
		pageNo = 1;
		orderBean.setPageNo(pageNo + "");
		orderBean.setStatus(type);//
		orderPresenter.getInfo(orderBean);
	}

	@Override
	public void onLoadMore() {
		// TODO Auto-generated method stub
		System.out.println("load");
		shuaxinType = "load";
		pageNo++;
		orderBean.setPageNo(pageNo + "");
		orderBean.setStatus(type);//
		orderPresenter.getInfo(orderBean);
	}

	public void stopLoad() {
		listView.stopLoadMore();
		listView.stopRefresh();
	}

}
